home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
- From: Dan Pop <danpop@mail.cern.ch>
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Sat, 20 Jan 1996 01:43:12 +0100
- Organization: CERN European Lab for Particle Physics
- Message-ID: <9601200043.AA10246@dxmint.cern.ch>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dorr8$i58@cloner3.netcom.com>
- X-NNTP-Posting-Host: hpl3sn03.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
- X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
-
- a1s@ix.netcom.com (Andrew Snyder) writes:
-
- >no tricks
- >
- >#define ISPOW2(x) (((x) & 1) ^ 1)
-
- Unless I'm missing something obvious, this macro returns 1 whenever x
- is even.
-
- A solution which actually works is:
-
- #define ISPOW2(x) (!((x) & (x) - 1))
-
- Its only bug is that ISPOW2(0) == 1. If this is a problem, the fix is:
-
- #define ISPOW2(x) ((x) && (!((x) & (x) - 1)))
-
- For best results, x should be unsigned (and with no side effects :-)
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-